package io.netty.test.main.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author LuoYu
 * @date 2018/10/27 10:46
 * <p>
 * Description:
 * 基于jdk
 * 阻塞式IO socket服务端
 */
public class Server {
    private ServerSocket serverSocket;

    public Server(int port) {
        try {
            this.serverSocket = new ServerSocket(port);
            System.out.println("bio server started at port :" + port);
        } catch (IOException e) {
            System.out.println("bio server start failed :" + e.getMessage());
        }
    }

    /**
     * 主线程创建子线程来处理客户端的阻塞连接
     */
    public void start(){
        System.out.println("current running thread:" + Thread.currentThread().getName());
        new Thread(() -> doAccept()).start();
    }

    /**
     * 接收客户端连接
     */
    private void doAccept(){
        for (;;) {
            try {
                System.out.println("current listen thread:" + Thread.currentThread().getName());
                // accept方法为阻塞的，当有客户端连接时才返回客户端连接
                Socket client = serverSocket.accept();
                // 处理客户端连接
                new ClientHandler(client).start();

            } catch (IOException e) {
                System.out.println("bio server accept client failed :" + e.getMessage());
            }
        }
    }

    public static void main(String[] args) {
        new Server(8080).start();
    }
}
